const endpoint = 'https://api.coze.cn/open_api/v2/chat';

// 检查环境变量并显示在页面上
const botIdElement = document.getElementById('env-bot-id');
const apiKeyElement = document.getElementById('env-api-key');
const replyElement = document.getElementById('reply');
const testApiButton = document.getElementById('test-api');

// 检查环境变量是否存在
const botId = import.meta.env.VITE_BOT_ID;
const apiKey = import.meta.env.VITE_API_KEY;

// 在控制台输出环境变量，用于调试
console.log('环境变量VITE_BOT_ID:', botId);
console.log('环境变量VITE_API_KEY:', apiKey);

// 更新页面显示环境变量状态
if (botId) {
  botIdElement.textContent = `BOT_ID: ${botId}`;
  botIdElement.classList.add('success');
} else {
  botIdElement.textContent = 'BOT_ID: 未找到环境变量 VITE_BOT_ID';
  botIdElement.classList.add('error');
}

if (apiKey) {
  // 只显示API密钥的前几个和后几个字符，中间用星号代替
  const maskedKey = apiKey.substring(0, 5) + '...' + apiKey.substring(apiKey.length - 5);
  apiKeyElement.textContent = `API_KEY: ${maskedKey}`;
  apiKeyElement.classList.add('success');
} else {
  apiKeyElement.textContent = 'API_KEY: 未找到环境变量 VITE_API_KEY';
  apiKeyElement.classList.add('error');
}

// API调用函数
async function callCozeApi() {
  if (!botId || !apiKey) {
    replyElement.textContent = '错误：缺少必要的环境变量，无法调用API';
    return;
  }
  
  replyElement.textContent = '正在调用API...';
  
  try {
    const payload = {
      bot_id: botId,
      user: 'yvo',
      query: '你好',
      chat_history: [],
      stream: false,
      custom_variables: {
        prompt: "你是一个AI助手"
      }
    };

    const response = await fetch(endpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${apiKey}`,
      },
      body: JSON.stringify(payload),
    });

    const data = await response.json();
    
    if (data.messages && data.messages.length > 0) {
      replyElement.textContent = data.messages[0].content;
    } else {
      replyElement.textContent = 'API返回数据格式不正确: ' + JSON.stringify(data);
    }
  } catch (error) {
    replyElement.textContent = `API调用出错: ${error.message}`;
    console.error('API调用出错:', error);
  }
}

// 添加按钮点击事件
testApiButton.addEventListener('click', callCozeApi);